<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Traits;

use App\Constants\ErrorCode;
use Hyperf\HttpServer\Contract\ResponseInterface;

trait Response
{
    /**
     * @Inject
     * @var ResponseInterface
     */
    protected $response;

    /**
     * 统一返回方法.
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function success(array $data = [], int $code = ErrorCode::SUCCESS, string $msg = null)
    {
        if (is_null($msg) || empty($msg)) {
            $msg = ErrorCode::getMessage($code);
        }
        $ret = [
            'code' => $code,
            'msg' => $msg,
            'data' => field_to_string($data),
        ];
        if ($code != ErrorCode::SUCCESS) {
            unset($ret['data']);
        }
        return $this->response->json($ret);
    }
}
